package top.archiesean.common.core.utils.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * @author ArchieSean
 * @description Bean获取工具类
 * @date 2023-12-31 22:53
 */
@Slf4j
@AutoConfiguration
public class SpringContextUtil implements ApplicationContextAware, DisposableBean {
    /**
     * spring容器
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }


    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 用于从容器中获取bean
     *
     * @param name bean名称
     * @return obj
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 用于从容器中获取map
     *
     * @param clazz clazz
     * @param <T>   T
     * @return map
     */
    public static <T extends Annotation> Map<String, Object> getBeansWithAnnotation(Class<T> clazz) {
        return getApplicationContext().getBeansWithAnnotation(clazz);
    }

    /**
     * 从容器中获取指定bean
     *
     * @param clazz 字节码
     * @param <T>   泛型
     * @return obj
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }


    /**
     * 清除SpringContextHolder中的ApplicationContext为Null.
     */
    public static void clearHolder() {
        if (log.isDebugEnabled()) {
            log.debug("清除SpringContextUtil中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }


    /**
     * 发布事件
     *
     * @param event 事件
     */
    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        applicationContext.publishEvent(event);
    }


    @Override
    public void destroy() throws Exception {
        SpringContextUtil.clearHolder();
    }
}
